//
//  HROrderInfoViewController.m
//  haierapp
//
//  Created by Xia Zhiyong on 14-8-14.
//  Copyright (c) 2014年 haier. All rights reserved.
//

#import "HROrderInfoViewController.h"
#import "HRSureOrderTableViewCell.h"
#import "HRSureOrderTableViewCell2.h"
#import "HRDeliveryTimeViewController.h"
#import "HRChoosePreferentialViewController.h"
#import "HRChooseAddressViewController.h"
#import "HRDebitNoteViewController.h"
#import "HRSubMitOrderViewController.h"
#import "HRProductInfo.h"
#import "HRAddressList.h"
#import "HRGoodsInfoViewController.h"

#import "HRGoodsInfo.h"
#import "HRStockCheckList.h"

@interface HROrderInfoViewController (){
    
    NSMutableArray *arrayInfo;
    NSMutableArray *arrayTypes;
    BOOL hasAddress; //是否有收货地址
    BOOL hasDefaultAddress; //是否有默认地址
    HRAddressInfo *infoAddress;
    
    NSString *paymentMethod;   //支付方式
    /*
    1.不限送货时间【0-周一至周日】
    2.工作日送货周一至周五【1-上午（9点至12点）,2-下午（12点至18点）】
    3.周末节假日送货周六至周日【3-上午（9点至12点）,4-下午（12点至18点）】
     */
    int distributionTime;  //送货时间类型
    
    int invoiceType; //发票类型
    
    NSString *invoiceName; //发票头
    
    int distributionType; //送货方式
    
    NSString *couponsId;
    int isCoupon;
    
    CGFloat _couponsAmount;//优惠券面额
    
}

@end

@implementation HROrderInfoViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        arrayInfo = [[NSMutableArray alloc] initWithObjects:@"",@"支付方式",@"配送方式",@"发货时间",@"电子发票",@"使用优惠券", nil];
        arrayTypes = [[NSMutableArray alloc] initWithObjects:@"",@"支付宝快捷支付",@"海尔送装一体",@"不限发货时间",@"个人",@"", nil];

        hasAddress = NO;
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    if (__CUR_IOS_VERSION >= __IPHONE_7_0)
    {
        self.edgesForExtendedLayout= UIRectEdgeNone;
    }
    self.navigationItem.title = @"确认订单";
    
    
    if (_type==ORDER_CONFIRM_TYPE_DIRECTBUY) {
        //直接生成订单
        [self showCustomLoadingHud:kLoading inView:nil];
        [HRInterfaceManager getProductById:_productId completion:^(BOOL isSucceed, NSString *message, id data) {
            [self hideCustomLoadingHud];
            
            if (isSucceed) {
                HRGoodsInfo *goodsInfo=(HRGoodsInfo *)data;
                
                HRProductInfo *productInfo=[[HRProductInfo alloc]initWithGoodsInfo:goodsInfo];
                
                _arrayGoods=[NSMutableArray arrayWithObjects:productInfo, nil];
                
                [self configTotalPriceLabel];
                
                [self.tableView reloadData];
            }else{
                [self showTextHUD:message];
            }
            
        }];
    }else{
        
        if (_type == ORDER_CONFIRM_TYPE_ACTIVITY && _activityType==ACTIVITY_TYPE_PRE_PAYMENT) {
            
            //预付款
            NSString *prePaymentStr=[NSString stringWithFormat:@"支付订金:￥%@",_prePayment];
            [arrayTypes replaceObjectAtIndex:0 withObject:prePaymentStr];
        }else if (_type == ORDER_CONFIRM_TYPE_ACTIVITY){
            //实付款
            NSString *paymentStr=[NSString stringWithFormat:@"实付款:￥%@",_totalPrice];
            [arrayTypes replaceObjectAtIndex:0 withObject:paymentStr];
        }
        
        [self configTotalPriceLabel];
    
    }
    
    
    
    [self defaultParameters];
    
    [self loadAddressList];
}

//默认参数
-(void)defaultParameters{
    paymentMethod = @"支付宝支付";
    distributionTime = 1;
    invoiceType = 0 ;
    invoiceName = @"个人";
    distributionType = 0;
    couponsId = @"";
    isCoupon = 0;
    
}

//配置合计价格
-(void)configTotalPriceLabel{
    //合计价格
    CGFloat price = 0.0f;
    
    if (_type==ORDER_CONFIRM_TYPE_ACTIVITY) {
        
        if (_activityType==ACTIVITY_TYPE_PRE_PAYMENT) {
            price=[_prePayment floatValue];
        }else{
            price=[_totalPrice floatValue];
        }
        
    }else{
        for (HRProductInfo *info in _arrayGoods) {
            price += [info.price integerValue]*[info.goodsAmount integerValue];
        }
    }
    
    price -= _couponsAmount;
    
    _lblTotalPrice.text = [NSString stringWithFormat:@"%.2f",price];

}

-(void)loadAddressList{
    [self showCustomLoadingHud:kLoading inView:nil];
    [HRInterfaceManager getReceiveAddressList:^(BOOL isSucceed, NSString *message, id data) {
        [self hideCustomLoadingHud];
        
        if (isSucceed) {
            HRAddressList *model = (HRAddressList*)data;
            NSArray *arrayAddress = [NSArray arrayWithArray:model.list];
            if (arrayAddress.count) {
                hasAddress = YES;
                for (HRAddressInfo *info in arrayAddress) {
                    if ([info.defaultAddress isEqualToString:DEFAULT_ADDRESS]) {
                        infoAddress = info;
                        [self refreshAddress];
                        hasDefaultAddress = YES;
                        break;
                    }
                    
                }
                
            }else{
                hasAddress = NO;
            }
        }else{
            [self showTextHUD:message];
        }
    }];
}

//刷新收货地址
-(void)refreshAddress{
    _viewNoAddress.hidden = YES;
    _viewHasAddress.hidden = NO;
    _lblBuyer.text = [NSString stringWithFormat:@"收件人: %@ %@",infoAddress.consignee,infoAddress.phone];
    _lblAddress.text = [NSString stringWithFormat:@"%@%@%@%@",infoAddress.provinceName,infoAddress.cityName,infoAddress.sectionName,infoAddress.addressDetail];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


#pragma mark - UITableViewDelegate
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 2;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section == 0) {
        return _arrayGoods.count;
    }else{
        
        int count=arrayInfo.count - 1;
        
        if (_type==ORDER_CONFIRM_TYPE_ACTIVITY) {
            count++;
        }
        
        return count;
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        return 80;
    }else{
        return 45;
    }
}

-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        static NSString *identifier = @"HRSureOrderTableViewCell";
        HRSureOrderTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
        if (!cell) {
            cell = [[HRSureOrderTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
        }
        
        [cell configWithData:[_arrayGoods objectAtIndex:indexPath.row]];
        return cell;
        
    }else{
        static NSString *identifier2 = @"HRSureOrderTableViewCell2";
        
        int indicatorIndex=2;
        int index=indexPath.row + 1;
        if (_type==ORDER_CONFIRM_TYPE_ACTIVITY) {
            indicatorIndex=3;
            index=indexPath.row;
        }
        
        HRSureOrderTableViewCell2 *cell = [tableView dequeueReusableCellWithIdentifier:identifier2];
        if (!cell) {
            cell = [[HRSureOrderTableViewCell2 alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier2];
            if (indexPath.row>=indicatorIndex) {
                cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
            }else{
                cell.accessoryType = UITableViewCellAccessoryNone;
            }
        }
        cell.lblName.text = [arrayInfo objectAtIndex:index];
        cell.lblType.text = [arrayTypes objectAtIndex:index];
        
        return cell;
    }

}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if (indexPath.section == 1) {
        HRSureOrderTableViewCell2 *cell = (HRSureOrderTableViewCell2*)[tableView cellForRowAtIndexPath:indexPath];
        
        int index=indexPath.row;
        
        if (_type==ORDER_CONFIRM_TYPE_ACTIVITY) {
            index=indexPath.row-1;
        }
        
        switch (index) {
            case 0:
                
                break;
            case 1:
                break;
            case 2:{

                HRDeliveryTimeViewController *viewC = [[HRDeliveryTimeViewController alloc] initWithNibName:@"HRDeliveryTimeViewController" bundle:nil];
                viewC.chooseTime = ^(NSString *timeStr,NSString* timeCode){
                    cell.lblType.text = timeStr;
                    
                    [arrayTypes replaceObjectAtIndex:3 withObject:timeStr];
                    
                    
                    distributionTime = [timeCode intValue];
                };
                [self.navigationController pushViewController:viewC animated:YES];
                break;
            }
            case 3:{
                HRDebitNoteViewController *viewC = [[HRDebitNoteViewController alloc] initWithNibName:@"HRDebitNoteViewController" bundle:nil];
                viewC.ChooseNote = ^(NSString *note){
                    cell.lblType.text = note;
                    
                    [arrayTypes replaceObjectAtIndex:4 withObject:note];
                    
                    invoiceType = 1;
                };
                [self.navigationController pushViewController:viewC animated:YES];
                break;
            }
            case 4:{
                HRChoosePreferentialViewController *viewC = [[HRChoosePreferentialViewController alloc] initWithNibName:@"HRChoosePreferentialViewController" bundle:nil];
                viewC.priceStr = _lblTotalPrice.text;
                viewC.choosePreferential = ^(NSString *str,NSString *couponId){
                    
                    if (![couponId isEqualToString:@""]) {
                        
                        //选择了优惠券
                        cell.lblType.text = [NSString stringWithFormat:@"%@元优惠券",str];
                        
                        [arrayTypes replaceObjectAtIndex:5 withObject:str];
                        
                        _couponsAmount = [str floatValue];
                        
                        isCoupon = 1;
                        couponsId = couponId;
                    }else{
                        //未选择优惠券
                        cell.lblType.text = @"";
                        
                        [arrayTypes replaceObjectAtIndex:5 withObject:str];
                        
                        _couponsAmount = [str floatValue];
                        
                        isCoupon = 0;
                        couponsId = couponId;
                    }
                    
                    
                    
                    //重新计算价格
                    [self configTotalPriceLabel];
                };
                [self.navigationController pushViewController:viewC animated:YES];
            }
                break;
            default:
                break;
        }
    }else{
        HRProductInfo *info = [_arrayGoods objectAtIndex:indexPath.row];
        HRGoodsInfoViewController *viewC = [[HRGoodsInfoViewController alloc] initWithNibName:@"HRGoodsInfoViewController" bundle:nil];
        viewC.goodsId = info.productId;
        [self.navigationController pushViewController:viewC animated:YES];
       
    }
}

- (IBAction)actionChooseBuyer:(id)sender {
    HRChooseAddressViewController *viewC = [[HRChooseAddressViewController alloc] initWithNibName:@"HRChooseAddressViewController" bundle:nil];
    viewC.passAddress = ^(HRAddressInfo *address){
        infoAddress = address;
        [self refreshAddress];
    };
    [self.navigationController pushViewController:viewC animated:YES];
}

- (IBAction)actionSure:(id)sender {
    
    if (!infoAddress) {
        [self showTextHUD:@"请选择收货地址"];
        return;
    }
    
    //库存校验
    [self checkStackBySectionCode:infoAddress.sectionCode];

}

//检测库存
-(void)checkStackBySectionCode:(NSString *)sectionCode{
    
    NSMutableArray *productListArray=[[NSMutableArray alloc]init];
    
    NSMutableArray *array = [[NSMutableArray alloc] init];
    for (HRProductInfo *info in _arrayGoods) {
        
        NSString *productName=[info.name stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        //检测库存的商品
        NSDictionary *productIdDic=[NSDictionary dictionaryWithObjectsAndKeys:
                                    info.productId,@"productId",
                                    productName,@"productName",
                                    nil];
        [productListArray addObject:productIdDic];
    }
    
    [self showCustomLoadingHud:kLoading inView:nil];
    [HRInterfaceManager checkStockByProductId:productListArray withSectionCode:sectionCode completion:^(BOOL isSucceed, NSString *message, id data) {
        [self hideCustomLoadingHud];
        
        if (isSucceed) {
            
            BOOL hasStock=YES;
            //NSMutableString *promptMsg=[[NSMutableString alloc]initWithString:@""];
            NSString *promptMsg=@"";
            HRStockCheckList *stockCheckList=(HRStockCheckList*)data;
            
            for (HRStockCheck *stockCheck in stockCheckList.list) {
                int useQty=[stockCheck.useQty intValue];
                
                if (useQty==0) {
                    hasStock=NO;
                    //[promptMsg appendFormat:@"商品:%@ 没有库存;",stockCheck.productName];
                    promptMsg=@"没有库存";
                }else{
                    //购买的商品数量
                    int productCount=0;
                    for (HRProductInfo *info in _arrayGoods) {
                        if ([info.productId isEqualToString:stockCheck.productId]) {
                            productCount=[info.goodsAmount intValue];
                            break;
                        }
                    }
                    
                    if (productCount>useQty) {
                        //购买数量超出库存
                        hasStock=NO;
                        //[promptMsg appendFormat:@"商品:% 数量超出库存;",stockCheck.productName];
                        promptMsg=@"购买数量超出库存";
                    }
                }
                
            }
            
            if (hasStock) {
                //创建订单
                [self createOrder];
            }else{
                //显示库存校验信息
                [self showTextHUD:promptMsg];
            }
            
        }else{
            [self showTextHUD:message];
        }
        
    }];
    
}

//创建订单
-(void)createOrder{
    
    NSMutableArray *array = [[NSMutableArray alloc] init];
    for (HRProductInfo *info in _arrayGoods) {
        NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
        [dic setObject:[NSString stringWithFormat:@"%@",info.productId] forKey:@"id"];
        [dic setObject:[NSString stringWithFormat:@"%@", info.goodsAmount ] forKey:@"num"];
        NSMutableArray *valueArray = [[NSMutableArray alloc] init];
        if (info.proSpeInfo.count) {
            for (HRProSpeInfo *speInfo in info.proSpeInfo) {
                [valueArray addObject:[speInfo toDictionary]];
            }
        }
        [dic setObject:valueArray forKey:@"value"];
        [array addObject:dic];
    }

    
    //创建订单
    [self showCustomLoadingHud:kLoading inView:nil];
    [HRInterfaceManager createOrder:infoAddress.receiveAddressId paymentMethod:paymentMethod distributionTime:distributionTime invoiceType:invoiceType invoiceName:invoiceName isCoupon:isCoupon couponsId:(NSString*)couponsId remark:@"" distributionType:distributionType productList:array isActivity:_activityType activityId:_activityId completion:^(BOOL isSucceed, NSString *message, id data) {
        [self hideCustomLoadingHud];
        
        [HRCommonData shareCommonData].hasNewShopCar=YES; //通知购物车已变化
        [HRCommonData shareCommonData].hasNewOrder=YES; //通知订单列表已变化
        
        if (isSucceed) {
            
            HRSubMitOrderViewController *submitOrderViewController = [[HRSubMitOrderViewController alloc] initWithNibName:NIBNAME_ORDER_SUBMIT bundle:nil];
            if ([data isKindOfClass:[NSDictionary class]]) {
                submitOrderViewController.orderNum = [NSString stringWithFormat:@"%@",[data objectForKey:@"orderNo"]];
                submitOrderViewController.price=[NSString stringWithFormat:@"%@",[data objectForKey:@"payAmount"]];
            }
            //submitOrderViewController.price = _lblTotalPrice.text;
            NSString *subject = @"";
            for (HRProductInfo *info in _arrayGoods){
                subject = [NSString stringWithFormat:@"%@ %@",subject,info.name];
            }
            submitOrderViewController.subject = subject;  //商品名称
            [self.navigationController pushViewController:submitOrderViewController animated:YES];
        }else{
            [self showTextHUD:message];
        }
    }];
}




@end
